/*
 *所有关于tb_project_apply_basicinfo类的业务代码应在此处编写
*可使用repository.调用常用方法，获取EF/Dapper等信息
*如果需要事务请使用repository.DbContextBeginTransaction
*也可使用DBServerProvider.手动获取数据库相关信息
*用户信息、权限、角色等使用UserContext.Current操作
*tb_project_apply_basicinfoService对增、删、改查、导入、导出、审核业务代码扩展参照ServiceFunFilter
*/
using MYData.Core.BaseProvider;
using MYData.Core.Extensions.AutofacManager;
using MYData.Entity.DomainModels;
using System.Linq;
using MYData.Core.Utilities;
using System.Linq.Expressions;
using MYData.Core.Extensions;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.AspNetCore.Http;
using MYData.System.IRepositories;
using MYData.Core.EFDbContext;
using MYData.System.IServices;
using System.Threading.Tasks;
using EFCore.BulkExtensions;
using MYData.Core.Infrastructure;
using System.Collections.Generic;
using MYData.Entity.DomainModels.ApiEntity.detail;
using Mapster;
using MYData.Entity.DomainModels.ApiEntity.Input;
using SkiaSharp;
using System.Threading.Tasks;
 
using MYData.Core.Utilities.Response;
using System;
using Microsoft.AspNetCore.Identity;
using MYData.Core.ManageUser;
using System.Diagnostics;
using MYData.Core;
using Newtonsoft.Json;

namespace MYData.System.Services
{
    public partial class tb_project_apply_basicinfoService : Itb_project_apply_basicinfoService
    {
        private readonly IHttpContextAccessor _httpContextAccessor;
        private readonly Itb_project_apply_basicinfoRepository _repository;//访问数据库
        private readonly Itb_project_workflowtableRepository _workRepository;
        private readonly VOLContext _db;
        [ActivatorUtilitiesConstructor]
        public tb_project_apply_basicinfoService(
            Itb_project_apply_basicinfoRepository dbRepository,
            IHttpContextAccessor httpContextAccessor,
            Itb_project_workflowtableRepository workRepository,
            VOLContext db
            )
        : base(dbRepository)
        {
            _httpContextAccessor = httpContextAccessor;
            _repository = dbRepository;
            _workRepository = workRepository;
            _db = db;
            //多租户会用到这init代码，其他情况可以不用
            //base.Init(dbRepository);
        }
        WebResponseContent webResponse = new WebResponseContent();
        UserInfo userInfo = UserContext.Current.UserInfo;

        /// <summary>
        /// 项目列表显示
        /// </summary>
        /// <returns></returns>
        /// WJQ 2023
        public async Task<WebResponseContent> GetBasicInfo(string projectName = "")
        {
            //var progress = GetProgress("1644522735000489984");
            var list = from x in _db.Set<tb_project_apply_basicinfo>().ToList()
                       join y in _db.Set<tb_project_sourceinfo>().ToList() on x.sourceName equals y.Id
                       join z in _db.Set<tb_project_appendix>().ToList() on x.projectID equals z.projectID
                       where x.isDelete == 0
                       select new
                       {
                           x.projectName,
                           x.declarantName,
                           y.dicValue,
                           y.Id,
                           x.projectID,
                           z.appendixName,
                           z.appendixID,
                           declarationTime = x.declarationTime.ToString("yyyy-MM-dd"),
                           progress = tb_project_workflowstepService.Instance.GetProgress(x.projectID, "tb_project_apply_basicinfo"),
                           operate = tb_project_workflowstepService.Instance.GetOperate(x.projectID, "tb_project_apply_basicinfo") == null ? "" : JsonConvert.SerializeObject(tb_project_workflowstepService.Instance.GetOperate(x.projectID, "tb_project_apply_basicinfo"))
                       };
            if (!string.IsNullOrEmpty(projectName))
            {
                list = list.Where(x => x.projectName.Contains(projectName));
            }
            return webResponse.OK("显示成功", list);
        }
        


        /// <summary>
        /// 根据附件表主键显示基础信息表+附件表详情信息
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        /// WJQ 2023
        public async Task<WebResponseContent> GetDetail(string id)
        {
            var list = from x in _db.Set<tb_project_appendix>().Where(x => x.appendixID == id)
                       join z in _db.Set<tb_project_apply_basicinfo>() on x.projectID equals z.projectID
                       select new
                       {
                           x,
                           z,
                       };
            return webResponse.OK("显示成功", list);
        }

        /// <summary>
        /// 根据基础信息表主键显示详情信息
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        /// WJQ 2023/4/11
        public async Task<WebResponseContent> basicDetail(string id)
        {
            var list = from x in _db.Set<tb_project_apply_basicinfo>().Where(x => x.projectID == id)
                       join z in _db.Set<tb_project_sourceinfo>() on x.sourceName equals z.Id
                       where x.isDelete==0 
                       select new
                       {
                           x.projectName,
                           z.dicValue,
                           x.declarantName,
                           x.projectID,
                       };
            return webResponse.OK("显示成功", list);
        }

        ///// <summary>
        ///// 逻辑删除申报基础信息表+附件表
        ///// </summary>
        ///// <param name="id"></param>
        ///// <returns></returns>
        ///WJQ 2023
        public async Task<WebResponseContent> DeleteBasicinfoorAppendix(string id)
        {
            ////开启事务   
            //_db.Database.BeginTransaction();
            //try
            //{
            //根据主表查询出来的数据查询附件表中相关数据
            var appendix = _db.Set<tb_project_appendix>().Find(id);
            //根据传过来的id查询申报基础信息表中需要的一条数据
            var basicinfolist = _db.Set<tb_project_apply_basicinfo>().Find(appendix.projectID);
            //逻辑删除修改申报基础信息表中的删除字段状态
            basicinfolist.isDelete = 1;
            //逻辑删除修改附件表中的删除字段状态
            appendix.isDelete = 1;
            //修改申报基础信息表数据
            _db.UpdateRange(basicinfolist);//,list1);
                                           //修改附件表数据
            _db.UpdateRange(appendix);
            //返回成功执行的行数
            await _db.SaveChangesAsync();
            //返回
            return webResponse.OK("删除成功");
            //}
            //catch (global::System.Exception)
            //{
            //    _db.Database.RollbackTransaction();
            //    return webResponse.Error("删除失败！！！");
            //}
        }

        /// <summary>
        /// 修改申报基础信息表+附件表
        /// </summary>
        /// <param name="detaildto"></param>
        /// <returns></returns>
        /// WJQ 2023
        public async Task<WebResponseContent> UpdateBasicinfoorAppendix(BasicinfoorAppendixDetail_Dto detaildto)
        {
            //    _db.Database.BeginTransaction();
            //    try
            //    {
            // 将输入Dto转换为领域模型
            // 把输入DTO转换成tb_project_apply_basicinfo实体
            var model = detaildto.Adapt<tb_project_apply_basicinfo>();
            // 把输入DTO中的数据转换成tb_project_appendix实体列表 
            var model1 = detaildto.data.Adapt<tb_project_appendix>();
            // 修改基本信息到数据库
            _repository.Update(model);
            // 修改数据到关联表 
            tb_project_appendixService.Instance.UpdateList(model1);
            await _repository.SaveChangesAsync();
            //返回
            return webResponse.OK("修改成功");
            //}
            //catch (global::System.Exception)
            //{
            //    _db.Database.RollbackTransaction();
            //    return webResponse.Error("修改失败！！！");
            //}

        }
        /// <summary>
        /// 添加申报基础信息表+附件表
        /// </summary>
        /// <param name="inputdto"></param>
        /// <returns></returns>
        /// WJQ 2023

        public async Task<WebResponseContent> AddBasicinfoorAppendix(BasicinfoorAppendixInput_Dto inputdto)
        {
            //_db.database.begintransaction();
            //try
            //{
            //定义一个雪花id
            string projectID = new Snowflake.Core.IdWorker(1, 1).NextId().ToString();
            // 将输入Dto转换为领域模型
            // 把输入DTO转换成tb_project_apply_basicinfo实体
            var model = inputdto.Adapt<tb_project_apply_basicinfo>();
            model.projectID = projectID;
            // 把输入DTO中的数据转换成tb_project_appendixInput_Dto实体列表 
            var model1 = inputdto.data.Adapt<tb_project_appendix>();
            //流程关系表添加
            tb_project_workflowtable workflowtable = new tb_project_workflowtable();
            //查询流程表中是否有这个表
            var workFlow = _db.Set<Sys_WorkFlow>().Where(x => x.WorkTable == "tb_project_apply_basicinfo").FirstOrDefault();
            workflowtable.workFlowId = workFlow.WorkFlow_Id;
            workflowtable.workName = workFlow.WorkName;
            workflowtable.projectTableKey = projectID;
            workflowtable.projectTable = workFlow.WorkTable;
            workflowtable.workTableName = workFlow.WorkTableName;
            workflowtable.currentOrderId = "1";//审批节点
            workflowtable.auditStatus = 0;//0默认为审核中
            workflowtable.createDate = DateTime.Now;
            workflowtable.creator = userInfo.UserName;
            model1.projectID = model.projectID;
            // 添加基本信息到数据库
            _repository.Add(model);
            //流程关系表添加
            _workRepository.Add(workflowtable, false);
            // 添加数据到关联表 
            tb_project_appendixService.Instance.AddList(model1);
            await _repository.SaveChangesAsync();
            //返回
            return webResponse.OK("添加成功");
            //}
            //catch (global::System.Exception)
            //{
            //    _db.Database.RollbackTransaction();
            //    return webResponse.Error("添加失败！！！");
            //}
        }
        /// <summary>
        /// 分配评审专家页面的项目数据的显示
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        /// WJQ 2023
        public async Task<WebResponseContent> ExpertInfo(string id)
        {
            var list = from x in _db.Set<tb_project_apply_basicinfo>().Where(x => x.projectID == id)
                       join z in _db.Set<tb_project_sourceinfo>() on x.sourceName equals z.Id
                       //join y in _db.Set<tb_project_reviewspecial_group>() on x.disciplineID equals y.panelID
                       select new
                       {
                           x.projectName,
                           x.declarantName,
                           x.sourceName,
                           z.dicValue,
                           z.Id,
                           x.declarationTime,
                           x.endTime,
                           x.disciplineID,
                       };
            return webResponse.OK("显示成功", list);
        }

        private class dto
        {
            public string? id { get; set; }
            public string? name { get; set; }
            public string? type { get; set; }
            public string? left { get; set; }
            public string? top { get; set; }
            public string? ico { get; set; }
            public string? state { get; set; }
            public string? stepValue { get; set; }
            public string? nodeType { get; set; }
            public string? userId { get; set; }
            public string? roleId { get; set; }
            public string? deptId { get; set; }
        }
    }
}
